/**
 * Created by lx on 2017/6/26.
 */

var candysModel = require('../models/candy');

var express = require('express');
var router = express.Router();




router.get('/getindexslist',function(req,res){
    candysModel.getindexsList(function(indexslist){
        res.status(200).json(indexslist)
    })
});

router.get('/getkoufulaislist',function(req,res){
    candysModel.getkoufulaisList(function(koufulaislist){
        res.status(200).json(koufulaislist)
    })
});

router.get('/getsenyongslist',function(req,res){
    candysModel.getsenyongsList(function(senyongslist){
        res.status(200).json(senyongslist)
    })
});

router.get('/getyoumanslist',function(req,res){
    candysModel.getyoumansList(function(youmanslist){
        res.status(200).json(youmanslist)
    })
});

//登录
router.get('/userlogin',function(req,res){
    res.render('login');
});
router.post('/login',function(req,res){
    var user = req.body;
    //判断用户是否点击登录按钮提交
    //if(user.submit == undefined){
    //    res.redirect('../views/login.html');
    //    return;
    //}
    //验证用户名和密码是否为空
    if(user.username == '' || user.password == ''){
        res.send("<script>alert('用户名或密码不能为空！');history.back();</script>")
        return;
    }
    var userinfo = {
        username:user.username,
        password:user.password
    };
    candysModel.login(userinfo,function(doc){
        if(doc){
            res.send("<script>alert('登录成功');location.href='/personalcenter/personalcenter'</script>")
        }else {
            res.send("<script>alert('登录失败');history.back();</script>")
        }
    })
});
//个人中心
router.get('/personalcenter', function (req,res) {
    res.render('personalcenter');
});


//注册
router.get('/register',function(req,res){
    res.render('register')
})
//检查注册
router.post('/registerinfo', function (req,res) {
    var user = req.body;
    //验证用户名和密码是否为空
    if(user.username == '' || user.password == ''){
        res.send("<script>alert('用户名或密码不能为空！');history.back();</script>")
        return;
    }
    var userinfo = {
        username:user.username,
        password:user.password
    };
    candysModel.add(userinfo, function (docs) {
        if(docs){
            res.send("<script>alert('注册成功');location.href='/api/candy/userlogin'</script>")
        }else {
            res.send("<script>alert('注册失败');history.back();</script>")
        }
    })
})

//购物车
router.get('/cartinfo', function (req,res) {
    var carts = req.query.username;
    console.log(carts)
    candysModel.getshoppingcartsInfo(carts,function(docs){
        res.status(200).json(docs);

    })
})

router.post('/addcart',function(req,res){
    var carts = req.body;
    console.log(carts);
    candysModel.addcart(carts, function (docs) {
            res.status(200).json({result:docs})
    })
})
router.get('/delcart', function (req,res) {
    var pid = req.query.id;
    candysModel.delcart(pid, function (docs) {
        res.status(200).json({result1:docs});
    })
})
module.exports = router;